import { loginAPI } from '@/apis/user'
import {useCartStore} from "@/stores/cartStore.js";
export const useUserStore = defineStore('user', () => {
    // 1. 定义管理用户数据的state
    const userInfo = ref({})
    const cartStore = useCartStore();
    // 2. 定义获取接口数据的action函数
    const getUserInfo = async (user) => {
        const res = await loginAPI(user)
        // userInfo.value = res.data
        const { username } = res.data.account; // 从 account 对象中提取 username
        const { userId } = res.data.account;
        let account=username
        const { token } = res.data; // 从响应中提取 token
        console.log("token"+token);

        // 将提取的值赋给 userInfo
        userInfo.value = { account, token, userId };
        await cartStore.updateLoginCartList();
    }
    // 退出时清除用户信息
    const clearUserInfo = () => {
        userInfo.value = {}
        cartStore.clearCart()
    }
    // 3. 以对象的格式把state和action return
    return {
        userInfo,
        getUserInfo,
        clearUserInfo,
    }
},{
    persist:true
})